class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        // 排序
        sort(intervals.begin(), intervals.end());
        // 排序后只用插入或更新右边界值
        vector<vector<int>> res;
        for(size_t i = 0; i < intervals.size(); ++i){
            int left = intervals[i][0], right = intervals[i][1];
            if(res.empty() || res.back()[1] < left)
                // 为空或区间无重叠，插入新区间
                res.push_back( {left, right} );   
            else
                // 区间有重叠更新右边界
                res.back()[1] = max(res.back()[1], right);
        }
        return res;
    }
};